package org.core.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import org.commons.model.APIException;
import org.commons.model.APIResult;
import org.core.entity.MessageEntity;
import org.core.service.MessageService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Yafei Song
 * @since 2022-08-10
 */
@RestController
@RequestMapping("/jt/message")
public class MessageController {

    @Resource
    private MessageService messageService;

    @Operation(summary = "根据id查找消息")
    @PostMapping("find")
    public APIResult<MessageEntity> find(Long id){
        return APIResult.ok(messageService.getById(id));
    }

    @Operation(summary = "获取消息列表")
    @PostMapping("list")
    public APIResult<Page<MessageEntity>> list(@RequestBody MessageEntity mes){
        LambdaQueryWrapper<MessageEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null!=mes.getMessageId(),MessageEntity::getMessageId,mes.getMessageId());
        queryWrapper.eq(null!=mes.getSerialNo(),MessageEntity::getSerialNo,mes.getSerialNo());
        List<MessageEntity> list = messageService.list(queryWrapper);
        Page<MessageEntity> page = new Page<>();
        page.setRecords(list);
        page.setCurrent(1);
        page.setSize(10);
        return APIResult.ok(page);
    }

    @Operation(summary = "添加消息")
    @PostMapping("add")
    public APIResult<Boolean> add(@RequestBody MessageEntity mes){
        return APIResult.ok(messageService.save(mes));
    }

    @Operation(summary = "更新消息")
    @PostMapping("update")
    public APIResult<Boolean> update(@RequestBody MessageEntity mes){
       return APIResult.ok(messageService.saveOrUpdate(mes));
    }

    @Operation(summary = "删除消息")
    @PostMapping("delete")
    public APIResult<Boolean> delete(Long id){
        MessageEntity message = messageService.getById(id);
        if (Objects.isNull(message)){
            throw new APIException(0,"未找到该信息");
        }
        message.setDelFlag(1);
        return APIResult.ok(messageService.saveOrUpdate(message));
    }
}

